<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>分时函数</title>
</head>
<body>
    
    <script>
        
       /*  -function () {
            // 这样直接for循环添加100个div，会造成浏览器卡死，非常耗费性能，这就引出了今天的分时函数
            let ary = [];
            for (let i = 0;i < 100;i++) {
                ary.push(i);
            }

            let renderList = function (data) {
                for (let i = 0,len = data.length;i < len;i++) {
                    let divEle = document.createElement('div');
                    divEle.innerHTML = data[i];
                    document.body.appendChild(divEle);    
                }
            }

            renderList(ary);
        } (); */

        
        -function () {
            // 分时函数 主要针对的是大量数据的处理
            // 比如要1秒钟创建 1000 个div；现在是要200ms 创建 8个

            function timeChunk (ary,fn,count) {
                let obj,t;
                let len = ary.length;
                let start = function () {
                    for (let i = 0;i < Math.min(count || 1,ary.length);i++) {
                        obj = ary.shift();
                        fn(obj);
                    }
                }

                return function () {
                    t = window.setInterval(function () {
                        if (ary.length === 0) {
                            clearInterval(t);
                        }
                        start();
                    },200) 
                }
            }

            let arr = [];

            for (let i = 0;i < 100;i ++) {
                arr.push(i);
            }

            let renderList = timeChunk (arr,function (n) {
                let divEle = document.createElement('div');
                divEle.innerHTML = n;
                document.body.appendChild(divEle);        
            },8) 

            renderList ();

        } ();
                    
    </script>
</body>
</html>